<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class source extends admin
{
    private $db;
    public $site;
    public $award_type;
    public $type;
    public $news;
    public $picture;
    public $video;
    public $sourceType;
    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->siteid = get_siteid(); // 获取当前站点
        $this->news = pc_base::load_model('news_nsr_model');
        $this->picture = pc_base::load_model('picture_nsr_model');
        $this->video = pc_base::load_model('video_nsr_model');
        $this->sourceType = pc_base::load_model('source_type_model');
        $this->db = pc_base::load_model('contest_source_model');
        $this->type = pc_base::load_model('source_type_model');
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
        $model_setting=pc_base::load_model('site_setting_model');//加载网站变量模型
		$this->setting = $model_setting->getValue("sname_link",$this->siteid);//获取来源名
		$this->author_title = $model_setting->getValue("author_title",$this->siteid);//获取作者职称
    }

    /**
     * 资源列表
     * source_type：资源类型；1资讯、2视频、图集
     */
    public function init()
    {
        //如果没获取到 contest_id，则视为非法请求
        if (! isset($_REQUEST['contest_id']) || empty($_REQUEST['contest_id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;#资源类型，默认1
        $typeid = isset($_GET['typeid']) ? $_GET['typeid'] : '';#资源分类
        if($source_type==1){
            $table="nsrweb_news_nsr";
            $btn_info="资讯";
        }elseif($source_type==2){
            $table="nsrweb_video_nsr";
            $btn_info="视频";
        }elseif($source_type==3){
            $table="nsrweb_picture_nsr";
            $btn_info="图集";
        }
		$select_categorys = $this->type->getSource($source_type,$typeid);
        $id = $_REQUEST['contest_id'];
        $contest_id = $_REQUEST['contest_id'];
        $model_contest = pc_base::load_model('contest_model'); // 加载model
        $data = $model_contest->get_one(array(
            'id' => $id
        ));
        $show_dialog = $show_validator = true;
        $show_header = '';
        $ids=$model_contest->child_id($id,2);
        $sql="SELECT n.*,c.id as cid,c.updated_by as supdated_by,c.is_top,c.sort,cn.name as cname  FROM nsrweb_contest_source AS c LEFT JOIN ".$table." AS n ON c.source_id = n.id left join nsrweb_contest as cn on c.contest_id =cn.id  WHERE n.`status` = 1";

        // 搜索框
        $title = isset($_GET['title']) ? $_GET['title'] : '';

        if (isset($_GET['search'])) {
            if ($title) {
                $sql .= " and n.`title` LIKE '%$title%'";
            }
            if ($typeid) {
                $sql .= " and n.type_id = {$typeid}";
            }
        }
        $ids=$model_contest->child_id($id,2);
        $sql.=" AND c.contest_id in ($ids) AND c.source_type = ".$source_type." AND n.siteid = ".$this->siteid." ORDER BY c.is_top DESC,c.sort DESC";

         $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
         $sourceinfo = $this->db->my_listinfo($sql, $page, 10);
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
         $pages = $this->db->pages;
        include $this->admin_tpl('contest_source_list');
    }

    /**
     * 添加
     */
    public function add()
    {

        if (isset($_POST['dosubmit'])) {

            $this->news = pc_base::load_model('news_nsr_model');
            $this->picture = pc_base::load_model('picture_nsr_model');
            $this->video = pc_base::load_model('video_nsr_model');
            $source_type=isset($_REQUEST['contest_source_type'])?$_REQUEST['contest_source_type']:1;

            if($source_type==1){
                $model=$this->news;
                $information =$model->check($_POST['information']);
            }elseif($source_type==2){
                $model=$this->video;
                $information =$model->check($_POST['manage']);
            }elseif($source_type==3){
                $model=$this->picture;
                $information =$model->check($_POST['picture']);
            }



            $id = $model->edit($information);
            //添加缓存
           // $this->news->redisCache($id);
            if ($id) {
                $data=array();
                $data['contest_id']=$_POST['contest_id'];
                $data['source_id']=$id;
                $data['source_type']=$source_type;
                $data['is_top']=0;
                $data['sort']=0;
                $data['created_by'] =  $_SESSION['userid'];
                $data['updated_by'] =  $_SESSION['userid'];

                $data['create_time'] = date("Y-m-d H:i:s",time());
                $data['update_time'] = date("Y-m-d H:i:s",time());
                $res = $this->db->insert($data);
                if ($res) {
//                     showmessage(L('add_success'), '?m=contest&c=source&a=init&contest_id='.$data['contest_id'],'','add');
					showmessage(L('add_success').L('2s_close'),'blank','','','function set_time() {$("#secondid").html(1);}setTimeout("set_time()", 500);setTimeout("window.close()", 1200);');
                } else {
                    showmessage(L('add_error'), HTTP_REFERER);
                }
            } else {
                showmessage(L('add_information_error'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;
            $types = $this->type->getSource($source_type);

            if (! isset($_REQUEST['contest_id']) || empty($_REQUEST['contest_id'])) {
                showmessage(L('illegal_action'), HTTP_REFERER);
            }
            $contest_id= $_REQUEST['contest_id'];
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);

            $action_source="contest_nsr";

            if($source_type==1){
                include $this->admin_tpl('information_add','information');
            }elseif($source_type==2){
                include $this->admin_tpl('manage_add','video');
            }elseif($source_type==3){
                include $this->admin_tpl('picture_add','picture');
            }

        }
    }


    /**
     * 删除、批量删除
     */
    public function del()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }
        $result = $this->db->delete("id in ('$id')");


        if ($result) {
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }


    public function bindView(){
        $contest_id= $_REQUEST['contest_id'];
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;
        $source_array=$this->db->select(array("contest_id"=>$contest_id,"source_type"=>$source_type),"source_id");

        $where=" status=1 and  siteid =" . $this->siteid;

        // 搜索框
        $keywords = isset($_GET['keywords']) ? $_GET['keywords'] : '';
        $typeid = isset($_GET['typeid']) ? $_GET['typeid'] : '';
        
        if (isset($_GET['search'])) {
            if ($keywords) {
                $where .= " and `title` LIKE '%$keywords%'";
            }
            if ($typeid) {
                $where .= " and type_id = {$typeid}";
            }
            
        }

        $select_categorys = $this->type->getSource($source_type,$typeid);
        
        if(!empty($source_array)){
            foreach ($source_array as $k => $v) {
                $id[] = intval($v['source_id']);
            }
            $id = implode('\',\'', $id);
            $where.=" and id not in ('$id')";
        }


        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        if($source_type==1){
            $model=$this->news;

        }elseif($source_type==2){
            $model=$this->video;

        }elseif($source_type==3){
            $model=$this->picture;

        }
        $url = "?m=contest&c=source&a=bindTypeSource&source_type=".$source_type."&contest_id=".$contest_id;
        $show_dialog = $show_validator = true;
        $show_header = '';
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $adminInfo = $admin_model->getRealnameInfo();
        $infos=$model->listinfo($where,'id DESC',$page,10);
//         //根据type_id查询类型名称，组装数据
//         $sourceType = $model=$this->sourceType;
//         foreach ($infos as $key => $value){
//             $tmpData = $sourceType->getSourceType($value['type_id']);
//             $value['typeName'] = $tmpData[0]['cn_name'];
//             $infos[$key] = $value;
//         }
//         foreach ($infos as $key=>$value){
//             foreach ($adminInfo as $key2=>$value2){
//                 if($value['updated_by'] == $key2){
//                     $value['publisher'] = $value2;
//                     $infos[$key] = $value;
//                     break;
//                 }
//             }
//         }
//         $sourceType = $tmpData = $value = null;#销毁数据，较少内存压力
        $pages = $model->pages;
        if($source_type==1){
            include $this->admin_tpl('information_select',"information");
        }elseif($source_type==2){
            include $this->admin_tpl('video_select','video');
        }elseif($source_type==3){
            include $this->admin_tpl('picture_select','picture');
        }



    }

    /**
     * ajax一键导入类型下资源
     */
    public function bindTypeSource ()
    {
        $contest_id= (int) $_REQUEST['contest_id'];
        $source_type=isset($_REQUEST['source_type'])?(int)$_REQUEST['source_type']:1;
        $type_id = (int) $_REQUEST['type_id'];
        $typeInfo = $this->type->get_one(array('id'=>$type_id));
        if($source_type==1){
            $model=$this->news;
            $info_type='资讯';
        }elseif($source_type==2){
            $model=$this->video;
            $info_type='视频';
        }elseif($source_type==3){
            $model=$this->picture;
            $info_type='图集';
        }
        $source_id = $this->db->select(array('contest_id'=>$contest_id,'source_type'=>$source_type),'source_id');
        if(!empty($source_id)){
            $sqltmp = ' id not in (';
            foreach ($source_id as $ks=>$vs){
                $sqltmp .= "'".$vs['source_id']."',";
            }
            $sqltmp = substr($sqltmp, 0, -1);
            $sqltmp .=') and type_id = '.$type_id;
        }else{
            $sqltmp .=' type_id = '.$type_id;
        }
        
        if ($typeInfo['parentid'] > 0) {
            if($source_type==1){
                $model=$this->news;
            }elseif($source_type==2){
                $model=$this->video;
            }elseif($source_type==3){
                $model=$this->picture;
            }
            $info = $model->select($sqltmp,'id');
            $data=array();
            foreach($info as $k=>$v){

                $data[$k]['contest_id']=$contest_id;
                $data[$k]['source_id']=$v['id'];
                $data[$k]['source_type']=$source_type;
                $data[$k]['created_by'] =  $_SESSION['userid'];
                $data[$k]['updated_by'] =  $_SESSION['userid'];

                $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
                $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
            }
            $res=$this->db->multiInsert($data);
            if($res){
                echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功！"));
            }else{
                echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"一键导入失败！"));
            }
        } else {
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"请选择".$info_type."的二级分类 ！"));
        }
    }


    public function  bindAction(){
        $contest_id= $_REQUEST['contest_id'];
        $relation=$_REQUEST['relation'];
        $source=explode("|",$relation);
        $data=array();
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;


        foreach($source as $k=>$v){

            $data[$k]['contest_id']=$contest_id;
            $data[$k]['source_id']=$v;
            $data[$k]['source_type']=$source_type;
            $data[$k]['is_top']=0;
            $data[$k]['sort']=0;
            $data[$k]['created_by'] =  $_SESSION['userid'];
            $data[$k]['updated_by'] =  $_SESSION['userid'];

            $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
            $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
        }
        $res=$this->db->multiInsert($data);
        if($res){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"选择成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"选择失败"));
        }
    }


    public function  top(){
        $result = $this->db->update(array('is_top'=> $_GET['is_top']), array(
            'id' => $_GET['id']
        ));
        if($result){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"更新成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"更新失败"));
        }
    }

    /**
     * 资讯批量删除
     */
    public function deleteAll ()
    {

        if(isset($_GET['dosubmit'])) {
            $id = implode('\',\'', $_POST['ids']);

            $result = $this->db->delete("id in ('$id')");
            if ($result) {
                showmessage(L('del_success'), HTTP_REFERER);
            } else {
                showmessage(L('del_error'), HTTP_REFERER);
            }
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 排序
     */
    public function listorder() {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {

                $result = $this->db->update(array('sort'=>$listorder), array(
                    'id' => $id
                ));

            }
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

}